package com.wj.config.security.component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wj.pojo.User;
import com.wj.pojo.UserInfo;
import com.wj.service.IUserInfoService;
import com.wj.service.IUserService;
import com.wj.utils.IpUtil;
import com.wj.utils.RespBean;
import com.wj.utils.UserUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private IUserInfoService userInfoService;
    @Resource
    private IUserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest res, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
        resp.setContentType("application/json;charset=UTF-8");

        //获取请求ip
        Integer id = UserUtil.getCurrentUser().getId();
        String ipAddress = IpUtil.getIpAddress(res);
        String ipSource = IpUtil.getIpSource(ipAddress);

        User user = User.builder().id(id)//更新用户信息
                .ipAddr(ipAddress)
                .ipSource(ipSource)
                .lastLoginTime(LocalDateTime.now()).build();
        userService.updateById(user);

        //获取用户信息并返回
        UserInfo userInfo = userInfoService.getById(id);
        String successRes = new ObjectMapper().writeValueAsString(RespBean.success("登录成功",userInfo));
        resp.getWriter().print(successRes);
    }

}
